<template>
  <div style="justify-content: center;align-items: center;width: 100%;height: 100%;">
    <el-drawer v-model="drawer" title="I am the title" :with-header="false">
      <div v-for="(chunk, index) in js.chunks" :key="index">
        <div v-show="index === 0">一共有<span style="color: red;">{{ js.chunks.length }}</span>个问题</div>
        <h2 style="color: red;">问题{{ index + 1 }}</h2>
        <p><strong>问题位置：</strong> {{ chunk.full_title }}</p>
        <p v-if="chunk.content"><strong>问题内容：</strong> {{ chunk.content }}</p>
        <!-- <p v-if="chunk.judge_type"><strong>Judge Type:</strong> {{ chunk.judge_type }}</p> -->
        <p v-if="chunk.judge_content"><strong>问题描述：</strong> {{ chunk.judge_content }}</p>
        <p v-if="chunk.revision_content"><strong>修改意见：</strong> {{ chunk.revision_content }}</p>
      </div>
    </el-drawer>
    <div class="component top-component" style='margin-top: 20px;'>
      <el-upload :limit="1" ref="uploadComponent" class="upload-demo" drag style="width: 55%; margin: 0 auto" action=""
        :http-request="upLoad" multiple :on-change="stopUpLoad">
        <el-icon class="el-icon--upload"><upload-filled /></el-icon>
        <div class="el-upload__text">将文件拖入<em>或点击选择</em></div>
        <template #tip>
          <div class="el-upload__tip">只支持上传docx文件</div>
        </template>
      </el-upload>
    </div>
    <div style='margin-top: 20px;'>
      <el-select v-model="Norm" placeholder="请选择文件检查规范" style="width: 240px;margin-left : 55%; ">
        <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value"
          :disabled="item.disabled" />
      </el-select>
      <el-button type="primary" @click="onSubmit">开始检查</el-button>
    </div>
    <div style='margin-top: 30px;'>
      <el-table :data="List" style="width: 70%; margin: 0 auto" max-height="350">
        <el-table-column label="上传时间" prop="time" />
        <el-table-column label="原始文件" prop="docx_name">
          <template v-slot="scope">
            <div @click="downLoad(scope.row.org)">{{ scope.row.docx_name }}</div>
          </template>
        </el-table-column>
        <el-table-column label="处理状态" prop="statu">
          <template v-slot="scope">
            <span v-if="scope.row.mistake_num === null || scope.row.mistake_num === undefined">
              正在处理
            </span>
            <span v-else> 处理完成 </span>
          </template>
        </el-table-column>
        <el-table-column label="审核结果">
          <template v-slot="scope">
            <el-button v-if="scope.row.mistake_num > 0" type="danger" plain size="small" class="spacing"
              @click="drawer = true, js = scope.row.res_json">
              有{{ scope.row.mistake_num }}个问题
            </el-button>
            <el-button v-if="scope.row.mistake_num > 0" type="info" plain size="small" class="spacing"
              @click="downLoad(scope.row.res)">
              下载
            </el-button>
            <el-tag v-if="scope.row.mistake_num === 0" type="success">审核通过</el-tag>
          </template>
        </el-table-column>
      </el-table>
    </div>
  </div>
</template>

<script setup lang="ts">
defineOptions({
  name: "Dict",
  inheritAttrs: false,
});
import axios from 'axios'
import { reactive, ref, onMounted } from 'vue'
import { UploadFilled } from '@element-plus/icons-vue'
import {
  Fold,
  Menu as IconMenu,
  Location,
  Setting,
} from '@element-plus/icons-vue'
import Cookies from 'js-cookie'
let uploadComponent
const API_URL = 'http://182.254.135.15:4001/'
let js = {}
const Norm = ref('')
const List = reactive<any[]>([]);
const form = reactive({
  file: '',
  norm: '',
  time: '',
  cookie: ''
})

const drawer = ref(false)

sessionStorage.clear();
const options = [
  {
    value: 'norm1',
    label: '需求说明文档规范'
  },
  {
    value: 'norm2',
    label: '详细设计文档规范',
    disabled: true
  }
]

const getInfo = () => {
  axios({
    method: 'post',
    url: API_URL + '/get_info',
    headers: {
      'Content-Type': 'application/json; charset=utf-8'
    },
    data: { cookie: document.cookie }
  })
    .then((response) => {
      sessionStorage.clear();
      List.splice(0, List.length)
      List.push(...response.data.data.file_list)
      console.log(List)
      List.sort((a: any, b: any) => new Date(b.time) - new Date(a.time));
      if (response.data.data.id) {
        console.log('用户的cookies:', document.cookie)
        console.log('uuid:', response.data.data.id)
        Cookies.set('cookie', response.data.data.id)
        console.log('用户的cookies:', document.cookie)
      }
    })
    .catch((error) => {
      console.error('Error fetching data:', error)
    })
}
let intervalId;
onMounted(() => {
  getInfo(); // 首次加载时立即执行
  intervalId = setInterval(getInfo, 30000); // 每隔30秒执行一次
});

const upLoad = (v) => {
  console.log(v.file)
  form.file = v.file
  if (v.file.length > 1) {
    alert('只能上传一个文件！')
    uploadComponent.clearFiles()
  }
}

const onSubmit = async () => {
  console.log(form)
  console.log(Norm.value)
  if (!form.file) {
    alert('请选择上传文件')
  }
  if (!Norm.value) {
    alert('上传文件前必须选择规范')
    return
  }
  if (!form.file.name.endsWith('.docx')) {
    alert('只能上传.docx文件')
    return
  }
  let currentTime = new Date()
  let beijingTime = new Date(currentTime.getTime() + 8 * 60 * 60 * 1000)
  let formattedTime =
    beijingTime.getUTCFullYear() +
    '-' +
    ('0' + (beijingTime.getUTCMonth() + 1)).slice(-2) +
    '-' +
    ('0' + beijingTime.getUTCDate()).slice(-2) +
    ' ' +
    ('0' + beijingTime.getUTCHours()).slice(-2) +
    ':' +
    ('0' + beijingTime.getUTCMinutes()).slice(-2) +
    ':' +
    ('0' + beijingTime.getUTCSeconds()).slice(-2)
  let fromdata = new FormData()
  fromdata.append('file', form.file)
  console.log("123", form.file)
  fromdata.append(
    'json_data',
    JSON.stringify({ norm: Norm.value, upload_time: formattedTime, cookie: { cookie: document.cookie } })
  )
  console.log(fromdata)
  let res = await axios.post(API_URL + '/upload', fromdata, {
    headers: {}
  })
  console.log(res)
}

const downLoad = (res) => {
  console.log(res); // 打印文件路径，用于调试
  axios
    .post(API_URL + '/download', {
      file_path: res
    }, {
      responseType: 'blob' // 确保以 blob 形式接收数据
    })
    .then((response) => {
      console.log(response);
      // 处理下载逻辑，例如使用Blob和URL.createObjectURL
      // 创建Blob对象时指定文件类型
      const blob = new Blob([response.data], {
        type: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'
      });
      const url = window.URL.createObjectURL(blob);
      const link = document.createElement('a');
      link.href = url;
      const docx = res.split('/').pop();
      console.log(docx);
      link.setAttribute('download', docx); // 使用文件名作为下载名
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link); // 移除链接元素
      window.URL.revokeObjectURL(url); // 释放URL对象
    })
    .catch((error) => {
      console.error('Error downloading file:', error);
    });
}
</script>